package com.supor.aiot.common.ui.activity;

import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.android.baseconfig.base.BaseActivity;
import com.android.baseconfig.base.BasePresenter;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.views.CustomTitleBar;
import com.supor.aiot.common.R;
import com.supor.aiot.common.R2;
import com.supor.aiot.common.app.Constants;

import androidx.annotation.RequiresApi;
import butterknife.BindView;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: url页面展示 <br>
 * 作者: lei <br>
 * 日期: 2020/11/10 <br>
 */
public class WebActivity extends BaseActivity {
    @BindView(R2.id.ll_root)
    View ll_root;
    @BindView(R2.id.toolbar)
    CustomTitleBar toolbar;
    @BindView(R2.id.web_view)
    WebView webview;
    @BindView(R2.id.web_view2_layout)
    LinearLayout webview2Layout;
    @BindView(R2.id.view_line)
    View viewLine;
    private WebSettings webSetting;
    private String title = null;
    /**
     * 使用一个webview返回至最上层会重新加载URL，另起一个webview来处理外链
     */
    WebView webview2 = null;

    @Override
    protected int resourceId() {
        return R.layout.activity_web;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void initView() {
        super.initView();
        initWebView(webview);
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            int type = bundle.getInt(Constants.Key.param_type);
            String url = bundle.getString(Constants.Key.param_url);
            title = bundle.getString(Constants.Key.param_title);
            Logc.i("web type= " + type + ", url= " + url + ", title= " + title);
            // type	显示类型：
            // 0 H5页面自带标题栏，需原生适配状态栏
            // 1 H5页面不带标题栏，需原生添加标题栏
            // 2 H5页面自带标题栏，不需原生适配状态栏

            if (type == 0) {
                toolbar.setVisibility(View.GONE);
                int statusBarHeight = SystemUtils.getDefaultStatusHeight(this);
                ll_root.setPadding(ll_root.getPaddingLeft(), statusBarHeight,
                        ll_root.getPaddingRight(), ll_root.getPaddingBottom());
            } else if (type == 1) {
                toolbar.setVisibility(View.VISIBLE);
            } else if (type == 2) {
                toolbar.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(title)) {
                // 设置标题
                toolbar.setLeftText(title.trim());
            }
            toolbar.setIvLeftOnClickListener(v -> onBackPressed());
            toolbar.setTvLeftOnClickListener(v -> onBackPressed());
            webview.loadUrl(url);
            webview.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX,
                                           int oldScrollY) {
                    if (scrollY >= 30) {
                        if (viewLine.getVisibility() != View.VISIBLE) {
                            viewLine.setVisibility(View.VISIBLE);
                        }
                    } else {
                        if (viewLine.getVisibility() != View.GONE) {
                            viewLine.setVisibility(View.GONE);
                        }
                    }
                }
            });
        }
    }

    private void initWebView(WebView webview) {
        webview.setWebViewClient(new HetWebClient());
        webview.setHorizontalScrollBarEnabled(false);
        webSetting = webview.getSettings();
        webSetting.setDefaultTextEncodingName("GBK");
        // User settings
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口，如window.open()，默认为false
        webSetting.setJavaScriptEnabled(true);//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        webSetting.setSupportZoom(false);//是否可以缩放，默认true
        webSetting.setBuiltInZoomControls(false);//是否显示缩放按钮，默认false
        webSetting.setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式
        webSetting.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
        webSetting.setAppCacheEnabled(true);//是否使用缓存
        webSetting.setDomStorageEnabled(true);//DOM Storage

        webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);//打开WebView硬件加速
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) //5.0以上不能加载http与https混合内容
            webSetting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private class HetWebClient extends WebViewClient {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Logc.e("web onReceivedError" + ", errorCode= " + errorCode + ", description= " + description
                    + ", failingUrl= " + failingUrl);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            showLoading();
            Logc.i("web onPageStarted" + ", url= " + url + ", title= " + view.getTitle());
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Logc.d("web onPageFinished" + ", url= " + url + ", title= " + view.getTitle());
            if (!TextUtils.isEmpty(WebActivity.this.title) && webview2Layout.getVisibility() == View.GONE) {
                closeLoading();
                return;
            }
            String title = view.getTitle();
            if (!TextUtils.isEmpty(title)) {
                // 设置标题
                toolbar.setLeftText(title.trim());
            }
            closeLoading();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Logc.i("web Override" + ", url= " + request.getUrl());
            if (webview2Layout.getVisibility() == View.GONE) {
                createWebView2();
                webview2.clearCache(true);
                webview2.clearHistory();
                webview2.clearFormData();
                webview2Layout.setVisibility(View.VISIBLE);
                webview2.loadUrl(request.getUrl().toString());
                return true;
            }
            return false;
        }
    }

    @Override
    public void onBackPressed() {
        if (webview2 != null && webview2.canGoBack()) {
            webview2.goBack();
            return;
        }
        if (webview2Layout.getVisibility() == View.VISIBLE) {
            webview2Layout.setVisibility(View.GONE);
            webview2.clearCache(true);
            webview2.clearHistory();
            webview2.clearFormData();
            if (!TextUtils.isEmpty(webview.getTitle())) {
                // 设置标题
                toolbar.setLeftText(webview.getTitle().trim());
            }
            return;
        }
        if (webview.canGoBack()) {
            // webview.goBack();
            super.onBackPressed();
            return;
        }
        super.onBackPressed();
    }

    void createWebView2() {
        webview2Layout.removeAllViews();
        webview2 = new WebView(this);
        initWebView(webview2);
        webview2Layout.addView(webview2);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webview != null) {
            webview.destroy();
            webview = null;
        }
    }
}
